package com.jzo2o.orders.manager.strategy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.request.CouponUseBackReqDTO;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class OrderCancelStrategyManager {
    @Autowired
    private IOrdersManagerService ordersManagerService;
    @Autowired
    private CouponApi couponApi;

    Map<String, OrderCancelStrategy> strategyMap=new HashMap<>();
    //管理订单取消策略对象
    @PostConstruct
    public void init(){
        //获取所有实现OrderCancelStrategy接口的bean(策略对象)
        strategyMap = SpringUtil.getBeansOfType(OrderCancelStrategy.class);
    }
    //根据条件选择对应的取消策略
    @GlobalTransactional(rollbackFor = Exception.class)
    public void cancel(OrderCancelDTO orderCancelDTO){
        //根据订单id查询订单信息
        Orders orders = ordersManagerService.getById(orderCancelDTO.getId());
        if (ObjectUtil.isEmpty(orders)){
            throw new RuntimeException("订单不存在");
        }
        //给orderCancelDTO赋值
        BeanUtil.copyProperties(orders,orderCancelDTO);

        //添加退回优惠券的逻辑
        if(orders.getDiscountAmount().compareTo(new BigDecimal(0))>0){
            CouponUseBackReqDTO couponUseBackReqDTO = new CouponUseBackReqDTO();
            couponUseBackReqDTO.setOrdersId(orders.getId());
            couponUseBackReqDTO.setUserId(orders.getUserId());
            couponApi.useBack(couponUseBackReqDTO);
        }

        //获取key
       String  key = orderCancelDTO.getCurrentUserType()+":"+
               OrderStatusEnum.codeOf(orders.getOrdersStatus()).getCode();

        OrderCancelStrategy orderCancelStrategy = strategyMap.get(key);
        if (ObjectUtil.isEmpty(orderCancelStrategy)){
            throw new RuntimeException("订单取消策略不存在");
        }
        orderCancelStrategy.cancel(orderCancelDTO);
    }
}
